package indi.zhifa.engine.test.aop;


import indi.zhifa.core.auth.util.ITokenUtil;
import indi.zhifa.core.multidatasource.core.RoutingDataSourceMemo;
import indi.zhifa.core.multidatasource.core.ZfRoutingDataSource;
import indi.zhifa.engine.test.enums.EDbDomain;
import indi.zhifa.engine.test.token.AuthObject;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@RequiredArgsConstructor
@Component
@Aspect
public class DataSourceAutoSelectedAop {

    private final ITokenUtil mTokenUtil;
    private final RoutingDataSourceMemo mRoutingDataSourceMemo;

    @Before("@within(indi.zhifa.core.common.web.entity.ann.ZhiFaRestController)")
    public void doBefore(final JoinPoint joinPoint) {
        if(mTokenUtil.hasTokenObject()){
            AuthObject authObject = mTokenUtil.getAuthObject();
            ZfRoutingDataSource zfRoutingDataSource = mRoutingDataSourceMemo.get(EDbDomain.BUSY.getName());
            zfRoutingDataSource.set(authObject.getDbCode());
        }
    }

    public void doAfter(final JoinPoint joinPoint) {
        if(mTokenUtil.hasTokenObject()){
            AuthObject authObject = mTokenUtil.getAuthObject();
            ZfRoutingDataSource zfRoutingDataSource = mRoutingDataSourceMemo.get(EDbDomain.BUSY.getName());
            zfRoutingDataSource.clear();
        }
    }
}
